<?php

class PointController extends AdminController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	// public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function actionIndex()
	{
	}

	/**
	 * Point history
	 */
	public function actionHistory()
	{
		$model=new PointHistory('search');
		$model->unsetAttributes();  // clear any default values
		$model->action=1;
		
		if(isset($_GET['PointHistory'])) 
			$model->attributes=$_GET['PointHistory'];
		
		$this->render('history/grid',array(
			'model'=>$model,
		));
	}

	/**
	 * Export history
	 */
	public function actionExport() {
		Yii::import('application.extensions.phpexcel.Classes.PHPExcel');
		$objPHPExcel = new PHPExcel();
		// Set properties
		$objPHPExcel->getProperties()
			->setCreator("Widocom")
			->setLastModifiedBy("Lam Huynh")
			->setTitle('Export Sale History')
			->setSubject("Office 2007 XLSX Document")
			->setDescription("Sale History")
			->setKeywords("office 2007 openxml php")
			->setCategory("Sale");
		$objPHPExcel->getActiveSheet()->setTitle('Sale History'); 
		$objPHPExcel->setActiveSheetIndex(0);
		
		//render HEADER BEGIN
		$header = array(
			Yii::t('app', 'Nickname'),
			Yii::t('app', 'Profile ID'),
			Yii::t('app', 'Time'),
			Yii::t('app', 'Point Package'),
			Yii::t('app', 'Price'),
		);
		$colStart = 'A';
		$colEnd = chr(ord($colStart)+count($header)-1);
		$objPHPExcel->getActiveSheet()->fromArray($header, null, "{$colStart}1");
		$headerStyle =  array(
			'borders' => array(
				'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_MEDIUM,
					'color' => array('rgb' => 'FFFFFF')
				),
			)
		);
		$range = "{$colStart}1:{$colEnd}1";
		$objPHPExcel->getActiveSheet()->getStyle($range)->getFont()->setSize(13)->setBold(true);
		$objPHPExcel->getActiveSheet()->getStyle($range)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle($range)->getFill()->getStartColor()->setRGB('DBEAF9');
		$objPHPExcel->getActiveSheet()->getStyle($range)->getFont()->getColor()->setRGB('000000');
		$objPHPExcel->getActiveSheet()->getStyle($range)->applyFromArray($headerStyle);
		for($i=$colStart; $i<=$colEnd; $i++)
			$objPHPExcel->getActiveSheet()->getColumnDimension($i)->setAutoSize(true);

		// data
		$model=new PointHistory('search');
		$i = 2;
		foreach($model->search()->data as $data) {
			$row = array(
				$data->user->nickname,
				$data->user->profile_id,
				Yii::app()->format->formatTime($data->created_time),
				$data->package->name,
				$data->price,
			);
			$objPHPExcel->getActiveSheet()->fromArray($row, null, "{$colStart}{$i}");
			$i++;
		}
		
		//save file
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		for($level=ob_get_level();$level>0;--$level) {
			@ob_end_clean();
		}
		
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		header('Content-type: '.'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		$fileName = 'SaleHistory '.date('Y-m-d');
		header(sprintf('Content-Disposition: attachment; filename="%s.xlsx"', $fileName));
		header('Cache-Control: max-age=0');				
		$objWriter->save('php://output');			
		Yii::app()->end();   
	}

	/**
	 * Manage Packages
	 */
	public function actionFee()
	{
		$c = new CDbCriteria();
		// $c->order = 'id asc';
		$models = PointFee::model()->findAll($c);
		if (isset($_POST['PointFee'])) {
			// validate models
			$models = array();
			$hasError = false;
			foreach($_POST['PointFee'] as $id => $data) {
				$model =  PointFee::model()->findByPk($id);
				if (empty($data['effect_from']))
					$data['effect_from']=null;
				if (empty($data['effect_to']))
					$data['effect_to']=null;
				$model->attributes = $data;
				
				if (!$model->validate()) {
					$hasError = true;
				}
					
				$models[] = $model;
			}
			
			// save models
			if (!$hasError) {
				foreach($models as $model) {
					$model->save();
				}
				Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
				$this->redirect(array('fee'));
			}
		}
		
		$this->render('fee',array(
			'items'=>$models,
		));	
	}

	/**
	 * Manage Packages
	 */
	public function actionPackages()
	{
		$c = new CDbCriteria();
		// $c->order = 'name';
		$items = PointPackage::model()->findAll($c);
		$newItem= new PointPackage();
		if (isset($_POST['PointPackage'])) {
			switch($_POST['action']) {
				case 'create':
					$this->create($newItem, $_POST['PointPackage']['new']);
					break;
				case 'update':
					$this->update($items, $_POST['PointPackage']);
					break;
			}

		}
		
		$this->render('package/index',array(
			'items'=>$items,
			'newItem'=>$newItem,
		));	
	}

	public function create($model, $data)
	{
		$model->attributes = $data;
		
		if ($model->save()) {
			Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
			$this->redirect(array('packages'));
		}
	}

	public function update(&$models, $datas)
	{
		// validate models
		$models = array();
		$hasError = false;
		foreach($datas as $id => $data) {
			$model = $this->loadModel($id);
			$model->attributes = $data;
			
			if (!$model->validate()) {
				$hasError = true;
			}
				
			$models[] = $model;
		}
		
		// save models
		if (!$hasError) {
			foreach($models as $model) {
				$model->save();
			}
			Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
			$this->redirect(array('packages'));
		}
	}

	public function actionDelete($id) {
		$this->loadModel($id)->delete();
		Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
		$this->redirect(array('packages'));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=PointPackage::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
